/*
 * Copyright (C) 2012 Le Tuan Anh <anh.takaji@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package util;

import ezcms.exceptions.PresentationException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

/**
 *
 * @author Le Tuan Anh <anh.takaji@gmail.com>
 */
public class UploadUtil {
    
    private static final Logger logger = Logger.getLogger(UploadUtil.class.getName());
    
    public static String saveFile(ServletContext context, File source, String originalFileName)
            throws PresentationException {
        if (source == null) {
            throw new PresentationException("Cannot save null file");
        }
        String uploadLocation = getUploadFolder(context);
        String filename = null;
        File destination = null;
        // Try to get an un-used file name
        do {
            UUID uuid = UUID.randomUUID();
            String extension = "";
            if (originalFileName != null) {
                extension = FilenameUtils.getExtension(originalFileName);
            }
            //TODO: Get the real extension please
//                if ("tmp".equals(extension)) {
//                    extension = "";
//                }

            filename = Math.abs(uuid.getLeastSignificantBits())
                    + "" + (new Date()).getTime()
                    + Math.abs(uuid.getMostSignificantBits()) + "." + extension.toLowerCase();
            String newFilePath = FilenameUtils.concat(uploadLocation, filename);
            
            destination = new File(newFilePath);
            System.out.println("Attemping to upload a file to -> " + newFilePath);
        } while (destination.exists());
        try {
            FileUtils.copyFile(source, destination);
        } catch (IOException ex) {
            throw new PresentationException(ex);
        }
        logger.log(Level.INFO, "File has been uploaded to: {0}", filename);
        return filename;
    }
    
    public static InputStream getFile(ServletContext servletContext, String filename) throws FileNotFoundException {
        String uploadLocation = getUploadFolder(servletContext);
        String filePath = FilenameUtils.concat(uploadLocation, filename);
        return new FileInputStream(new File(filePath));
    }
    
    private static String getUploadFolder(ServletContext context) {
        String uploadLocation = context.getRealPath("/WEB-INF/uploads/FileResource/");
        return uploadLocation;
    }
    
    public static String getJasperTemplate(ServletContext context, String filename) {
        String jasperFolder = context.getRealPath("/WEB-INF/jasper/");
        return FilenameUtils.concat(jasperFolder, filename);
    }
}
